package com.algorithm.example.queue.queue;

import java.util.Iterator;

/**
 * <p>
 * 数组队列
 * </p>
 *
 * @author lzt
 * @version 1.0
 * @since 2024/1/24 18:10
 */
public class ArrayQueue<E> implements Queue<E>, Iterable<E> {

    private E[] array;

    private int head;
    private int tail;

    public ArrayQueue(int array) {
        this.array = (E[]) new Object[array + 1];
    }

    @Override
    public boolean offer(E value) {
        if(isFull()) {
            return false;
        }
        array[tail] = value;
        tail = (tail + 1) % array.length;
        return true;
    }

    @Override
    public E poll() {
        if(isEmpty()) {
            return null;
        }
        E e = array[head];
        // 垃圾回收
        array[head] = null;
        head++;
        return e;

    }

    @Override
    public E peek() {
        if(isEmpty()) {
            return null;
        }
        return array[head];
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return (tail + 1) % array.length == 0;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = 0;

            @Override
            public boolean hasNext() {
                return (p + 1) % array.length != 0;
            }

            @Override
            public E next() {
                E e = array[p];
                p++;
                return e;
            }
        };
    }
}
